package com.pda.common.pages.config;

import android.content.Context;
import com.apkfuns.logutils.LogUtils;
import com.pda.common.basemvp.model.BaseModel;
import com.pda.common.bean.BaseBean;
import com.pda.common.bean.ConfigBean;
import com.pda.common.bean.DealerBean;
import com.pda.common.bean.ProductBean;
import com.pda.common.beanin.ConfigInBean;
import com.pda.common.beanin.DownloadInBean;
import com.pda.common.database.DataBaseControl;
import com.pda.common.database.DealerInfo;
import com.pda.common.database.ProductInfo;
import com.pda.common.tools.SharedPreferencesManger;
import com.pda.common.tools.StringProcess;
import com.pda.common.utils.HttpConfig;
import com.pda.common.utils.PDAUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class ConfigModelImpl extends BaseModel implements ConfigModel {
    private String tag = "ConfigModelImpl";
    private BaseBean baseBean;
    private ProductBean productBean;
    private DealerBean dealerBean;
    private ConfigBean configBean;

    public ConfigModelImpl(Context context) {
        super(context);
    }

    @Override
    public void config(final String url, final String cid, final CallBack callBack) {
        PDAUtil.hostname = "http://" + url + "/";
        httpConfig = new Retrofit.Builder()
                .baseUrl(PDAUtil.hostname)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build().create(HttpConfig.class);
        try {
            ConfigInBean configInBean = new ConfigInBean();
            configInBean.setAction("CheckNet");
            configInBean.setCid(cid);
            RequestBody body = RequestBody.create(PDAUtil.JSON, gson.toJson(configInBean));
            httpConfig.config(body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new io.reactivex.Observer<ResponseBody>() {
                        private Disposable mDisposable;

                        @Override
                        public void onSubscribe(Disposable d) {
                            mDisposable = d;
                        }

                        @Override
                        public void onComplete() {
                            callBack.ontip("网络配置成功");
                            SharedPreferencesManger.setHostName(url);
                            SharedPreferencesManger.setCid(cid);
                            mDisposable.dispose();
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (baseBean.getErrmsg() != null && baseBean.getErrmsg().length() > 0) {
                                callBack.ontip(baseBean.getErrmsg());
                            } else {
                                callBack.ontip(PDAUtil.connectError);
                            }
                            mDisposable.dispose();
                        }

                        @Override
                        public void onNext(ResponseBody abBean) {
                            LogUtils.w(StringProcess.responsetoString(abBean));
                            baseBean = gson.fromJson(StringProcess.responsetoString(abBean), BaseBean.class);
                            if (baseBean != null && baseBean.getErrcode() == 0) {
                                onComplete();
                            } else {
                                onError(new Throwable());
                            }
                        }
                    });
        } catch (Exception e) {
            callBack.ontip(PDAUtil.connectError);
            e.printStackTrace();
        }
    }

    @Override
    public void download(final int type, final CallBack callBack) {
        try {
            DownloadInBean downloadInBean = new DownloadInBean();
            downloadInBean.setAction("DownloadBaseInfo");
            downloadInBean.setCid(SharedPreferencesManger.getCid());
            downloadInBean.setUserID("-1");
            downloadInBean.setStoreID("-1");
            downloadInBean.setBaseType(type);
            RequestBody body = RequestBody.create(PDAUtil.JSON, gson.toJson(downloadInBean));
            httpConfig.download(body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new io.reactivex.Observer<ResponseBody>() {
                        private Disposable mDisposable;

                        @Override
                        public void onSubscribe(Disposable d) {
                            mDisposable = d;
                        }

                        @Override
                        public void onComplete() {
                            if(type==1){
                                callBack.ontips("同步产品信息"+productBean.getData().size()+"条");
                            }
                            else if(type==3)
                            {
                                callBack.ontips("同步经销商信息"+dealerBean.getData().size()+"条");
                            }
                            mDisposable.dispose();
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (baseBean.getErrmsg() != null && baseBean.getErrmsg().length() > 0) {
                                callBack.ontip(baseBean.getErrmsg());
                            } else {
                                callBack.ontip(PDAUtil.connectError);
                            }
                            mDisposable.dispose();
                        }

                        @Override
                        public void onNext(ResponseBody abBean) {
                            if (type == 1) {
                                LogUtils.w("t1:" + StringProcess.responsetoString(abBean));
                                productBean = gson.fromJson(StringProcess.responsetoString(abBean), ProductBean.class);
                                if (productBean != null && productBean.getErrcode() == 0) {
                                    DataBaseControl.deleteProductAll();
                                    for (int i = 0; i < productBean.getData().size(); i++) {
                                        ProductInfo productInfo = new ProductInfo(null, productBean.getData().get(i).getId(), productBean.getData().get(i).getCode(),
                                                productBean.getData().get(i).getName(), productBean.getData().get(i).getTuoCaseNum(), productBean.getData().get(i).getCaseBoxNum());
                                        DataBaseControl.addProduct(productInfo);
                                    }
                                    onComplete();
                                }
                                else
                                {
                                    onError(new Throwable());
                                }
                            } else if (type == 3) {
                                LogUtils.w("t3:" + StringProcess.responsetoString(abBean));
                                dealerBean = gson.fromJson(StringProcess.responsetoString(abBean), DealerBean.class);
                                if (dealerBean != null && dealerBean.getErrcode() == 0) {
                                    DataBaseControl.deleteDealerAll();
                                    for (int i = 0; i < dealerBean.getData().size(); i++) {
                                        DealerInfo dealerInfo = new DealerInfo(null, dealerBean.getData().get(i).getId(), dealerBean.getData().get(i).getCode(),dealerBean.getData().get(i).getName());
                                        DataBaseControl.addDealer(dealerInfo);
                                    }
                                    onComplete();
                                }
                                else
                                {
                                    onError(new Throwable());
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            callBack.ontip(PDAUtil.connectError);
            e.printStackTrace();
        }
    }

    @Override
    public void downloadConfig(final CallBack callBack) {
        try {
            DownloadInBean downloadInBean = new DownloadInBean();
            downloadInBean.setAction("DownloadConfig");
            downloadInBean.setCid(SharedPreferencesManger.getCid());
            downloadInBean.setUserID("-1");
            downloadInBean.setStoreID("-1");
            RequestBody body = RequestBody.create(PDAUtil.JSON, gson.toJson(downloadInBean));
            httpConfig.downloadconfig(body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new io.reactivex.Observer<ResponseBody>() {
                        private Disposable mDisposable;

                        @Override
                        public void onSubscribe(Disposable d) {
                            mDisposable = d;
                        }

                        @Override
                        public void onComplete() {
                            callBack.ontips("同步后台条码信息成功");
                            mDisposable.dispose();
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (configBean.getErrmsg() != null && configBean.getErrmsg().length() > 0) {
                                callBack.ontip(configBean.getErrmsg());
                            } else {
                                callBack.ontip(PDAUtil.connectError);
                            }
                            mDisposable.dispose();
                        }

                        @Override
                        public void onNext(ResponseBody abBean) {
                            LogUtils.w(StringProcess.responsetoString(abBean));
                            configBean = gson.fromJson(StringProcess.responsetoString(abBean), ConfigBean.class);
                                if (configBean != null && configBean.getErrcode() == 0) {
                                    SharedPreferencesManger.setBoxMix(configBean.getData().getBoxCodeLenMin());
                                    SharedPreferencesManger.setBoxMax(configBean.getData().getBoxCodeLenMax());
                                    SharedPreferencesManger.setCaseMix(configBean.getData().getCaseCodeLenMin());
                                    SharedPreferencesManger.setCaseMax(configBean.getData().getCaseCodeLenMax());
                                    onComplete();
                                }
                                else
                                {
                                    onError(new Throwable());
                                }
                        }
                    });
        } catch (Exception e) {
            callBack.ontip(PDAUtil.connectError);
            e.printStackTrace();
        }
    }
}

